package com.wzh.yebServe.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wzh.yebServe.pojo.Employee;
import com.wzh.yebServe.pojo.MailConstants;
import com.wzh.yebServe.pojo.MailLog;
import com.wzh.yebServe.service.IEmployeeService;
import com.wzh.yebServe.service.IMailLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author wzh
 * @create 2023/5/6 16:09
 * @Description:邮件发送定时任务
 */
@Component
@RequiredArgsConstructor
public class MailTask {

    private final IMailLogService iMailLogService;


    private final IEmployeeService iEmployeeService;


    private final RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/10 * * * * ?")
    public void mailTask(){
        List<MailLog> list = iMailLogService.list(new QueryWrapper<MailLog>().eq("status", MailConstants.DELIVERING).lt("tryTime", LocalDateTime.now()));
        list.forEach(mailLog -> {
            if (mailLog.getCount()>=3){
                iMailLogService.update(new UpdateWrapper<MailLog>().set("status", MailConstants.FAILURE).eq("msgId",mailLog.getMsgId()));
            }
            iMailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1)
                    .set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT)).set("updateTime",LocalDateTime.now()));

            List<Employee> emp = iEmployeeService.getEmployee(mailLog.getEid());
//            发送消息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,emp,new CorrelationData(mailLog.getMsgId()));
        });

    }
}
